package jwt

import (
	"errors"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/dgrijalva/jwt-go/v4"
	"strings"
)

var key string

type MyCustomClaims struct {
	UserId int64
	jwt.StandardClaims
}

func CreateJwt(claims *MyCustomClaims) (string, error) {
	key, _ = beego.AppConfig.String("MySigningKey")
	//fmt.Println(key)
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString([]byte(key))
	fmt.Printf("%v %v", ss, err)
	return ss, err
}

func VerificationToken(tk string) (int64, error) {
	if tk == "" {
		return 0, errors.New("请先登录！")
	}
	tkArr := strings.Split(tk, " ")
	token, err := jwt.ParseWithClaims(tkArr[1], &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(key), nil
	})
	if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
		fmt.Println("================================")
		fmt.Printf("%v %v", claims.UserId, claims.StandardClaims.ExpiresAt.Unix())
		fmt.Println("================================")
		return claims.UserId, nil
	} else {
		fmt.Println(err)
		return 0, err
	}
}

// VerificationTk 不含切片
func VerificationTk(tk string) (int64, error) {
	if tk == "" {
		return 0, errors.New("token不可以为空，请先认证")
	}
	token, err := jwt.ParseWithClaims(tk, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(key), nil
	})
	if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
		fmt.Println("================================")
		fmt.Printf("%v %v", claims.UserId, claims.StandardClaims.ExpiresAt.Unix())
		fmt.Println("================================")
		return claims.UserId, nil
	} else {
		fmt.Println(err)
		return 0, err
	}
}
